from prg.common.config_common import ConfigBase
from prg.common.common_base import CommonBase
from prg.entity.authority_entity import AuthorityEntity
from threading import Lock
from prg.entity.arg_entity import ArgBase


class AuthorityBll:
    _instance_lock = Lock()

    def __init__(self, path):
        authority = ConfigBase.get_config(name="user", path=path, en=AuthorityEntity())
        self.authority_dict = dict()
        for item in authority.config.user:
            self.authority_dict[item.name] = item
        # self.authority_dict = {item.name: item for item in authority.config.user}

    def get_user(self, name):
        if name in self.authority_dict:
            return self.authority_dict[name]
        return None

    def is_user(self, name):
        return name in self.authority_dict

    def check_user(self, name, psw):
        user = self.get_user(name)
        if user is not None and user.password == psw:
            return True
        return False

    def data_decrypt(self, name, data, en=None):
        user = self.get_user(name)
        if user is not None:
            json_entity = CommonBase.aes_decrypt_json(key=user.aes, data=data, en=en)
            return json_entity
        return None

    def data_encryption(self, name, data):
        user = self.get_user(name)
        if user is not None:
            encryption_str = CommonBase.aes_encryption(key=user.aes, data=data)
            return encryption_str
        return None

    @staticmethod
    def instance(path=None):
        if not hasattr(AuthorityBll, "_instance"):
            with AuthorityBll._instance_lock:
                if not hasattr(AuthorityBll, "_instance"):
                    AuthorityBll._instance = AuthorityBll(path)
        return AuthorityBll._instance
